package com.media.selector.sample

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.google.android.material.snackbar.Snackbar
import com.media.selector.MediaSelector
import com.media.selector.media.listener.OnMediaSelectorResultCallbacks
import com.media.selector.media.model.entity.MimeType
import com.media.selector.sample.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    companion object {
        private const val CAMERA_PERMISSIONS_REQUEST_CODE = 100
        private const val WRITE_AND_READ_PERMISSIONS_REQUEST_CODE = 101
    }

    private lateinit var mBinding: ActivityMainBinding
    private var isCaptureEnable = true

    // This is an array of all the permission specified in the manifest.
    private val mWriteAndReadPermissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
    private val mCameraPermissions = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        mBinding.mediaCamera.setOnClickListener { startCamera() }
        mBinding.mediaSelector.setOnClickListener {
            isCaptureEnable = true
            startMediaSelector()
        }
        mBinding.mediaPictures.setOnClickListener {
            isCaptureEnable = false
            startMediaSelector()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CAMERA_PERMISSIONS_REQUEST_CODE) {
            if (allPermissionsGranted(*mCameraPermissions)) {
                startCamera()
            } else {
                Snackbar.make(mBinding.mediaCamera, "Permissions not granted by the user.", Snackbar.LENGTH_LONG).setAction("Action", null).show()
            }
        } else if (requestCode == WRITE_AND_READ_PERMISSIONS_REQUEST_CODE) {
            if (allPermissionsGranted(*mWriteAndReadPermissions)) {
                startMediaSelector()
            } else {
                Snackbar.make(mBinding.mediaCamera, "Permissions not granted by the user.", Snackbar.LENGTH_LONG).setAction("Action", null).show()
            }
        }
    }

    /**
     * 检测是否授权
     */
    private fun allPermissionsGranted(vararg permissions: String) = permissions.all {
        ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED
    }

    private fun startCamera() {
        if (allPermissionsGranted(*mCameraPermissions)) {
            MediaSelector.with().takePhoto(this)
        } else {
            ActivityCompat.requestPermissions(this, mCameraPermissions, CAMERA_PERMISSIONS_REQUEST_CODE)
        }
    }

    private fun startMediaSelector() {
        if (allPermissionsGranted(*mWriteAndReadPermissions)) {
            MediaSelector.with()
                .choose(MimeType.ofImage())
                .capture(isCaptureEnable)
                .maxSelectable(1)
                .setMediaTypeExclusive(true)
                .showSingleMediaType(false)
                .showPreview(false)
                .start(this)
        } else {
            ActivityCompat.requestPermissions(this, mWriteAndReadPermissions, WRITE_AND_READ_PERMISSIONS_REQUEST_CODE)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        MediaSelector.with().onMediaSelectorResult(requestCode, data, object : OnMediaSelectorResultCallbacks() {
            override fun onTakePhotoResult(state: Boolean, path: String?) {
                mBinding.mediaSelectorPath.text = path
            }
            override fun onMediaSelectorResult(uris: List<Uri>?, paths: List<String>?) {
                mBinding.mediaSelectorPath.text = paths?.joinToString("\n\n")
            }
        })
    }
}
